/* SVN FILE: $Id: app_controller.js 37 2007-08-26 22:57:19Z killergeorge $ */
/**
 * To quote Dave Cardwell: 
 * Built on the shoulders of giants:
 *   * John Resig      - http://jquery.com/
 *
 * Jamal :  Javascript MVC Assembly Layout <http://jamal-mvc.com/>
 * Copyright (c)    2007, Timo Derstappen <http://teemow.com/>
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @copyright        Copyright (c) 2007, Timo Derstappen
 * @link            
 * @package          jamal
 * @subpackage       jamal.app
 * @since            Jamal v 0.4
 * @version          $Revision: 37 $
 * @modifiedby       $LastChangedBy: killergeorge $
 * @lastmodified     $Date: 2007-08-26 22:57:19 +0000 (Sun, 26 Aug 2007) $
 * @license          http://www.opensource.org/licenses/mit-license.php The MIT License
 */

/**
 * Jamal app controller
 *
 * @public
 * @cat controller
 */
$j.extend($j.fn.c.prototype, {
    components: ['session', 'modal','message','airCache','airSettings'],
	
	/**
	 * before the execution of every controller method
	 */
	beforeAction: function() {
    },
	
	/**
	 * after the execution of every controller method
	 */
    afterAction: function() {
    },
	
	
	
	/**
	 * the function wich will be needed to be removed on garbage collect
	 * @param {Array} - holding the listern functions in same order as the event types
	 */
	garbage_event_listeners: [], 
	
	/**
	 * the event types which have a function appended to them
	 * @param {Array} - holding the Event types in same order as the event listeners ary
	 */
	garbage_event_types: [], 
		
	/**
	 * append the main navigation to the navi div
	 * 
	 * this also appends the beforeWindoChange function which can be used to do some 
	 * garbage collection before a new html page is opened
	 * 
	 * @param {Object} activeMenu
	 */
	appendMainNav: function (activeMenu) {
		jamal.log("Start appController appendMainNav");
		//should be put in model and made with callback into controller
		$j.current.m.readMainNavXml(activeMenu, $j.current._createMenuFromXML);

	},
	
	
	/**
	 * add an event type with his asscoiated function onto garbage collector
	 * @param {Object} type
	 * @param {Object} listener
	 */
	addToGarbage: function (type, listener)
	{
		$j.current.garbage_event_listeners.push(listener);
		$j.current.garbage_event_types.push(type);		
		
	},
	
	/**
	 * before a link in the main nav is clicked and the window changes .. shows another html page
	 * this methods catches the click and invokes some cleanup methods.
	 * those are f.ex. AIR window events(DragEnter/DragExit) which stay consistently after the app has launched
	 */
	beforeWindowChange: function () {
		
		$('#navi ul li a').click( function (e) { //tabs-nav
			e.preventDefault();
			
			var listeners = $j.current.garbage_event_listeners;
			var types	  = $j.current.garbage_event_types;
						
			//remove window events ... should be other events later too
			//jamal.log(listeners);
			
			if(listeners.length > 0)
			{
				for(var i=0; i < listeners.length; i++)
				{
					$j.current._unbindAirWindowEvent(types[i], listeners[i]);
				}
			}
			//change location			
			location.href = this;
		});
	},
	
	/**
	* Called when the user closes the window.
	* this deletes the cache file
	*/
	windowClosingHandler: function (event) {		
		event.preventDefault();
		nativeWindow.removeEventListener("closing", $j.current.windowClosingHandler);
		jamal.airCache.flush();
		air.Shell.shell.exit();		
		
	},
	
	
	/**
	 * read a single file and return its contents
	 * @param {MIXED} file - STRING - the filename or a path/filename.js
	 * 									in this case a new file object will be created
	 * 						OBJECT - an existing file object
	 */
	readFile: function (file) {
		jamal.log("Start _readFile");
	
		if(typeof file == 'string')
		{//passed a filename string in so need to make a new fileobject
			var filename 	= file;	//cosmetics
			var base_dir	= $j.current.directory.nativePath;
			var file 	 	= new air.File();
			file 			= file.resolve(base_dir + filename );
		}	
		
		var stream = new air.FileStream();
		stream.open( file, air.FileMode.READ );
		data = stream.readMultiByte(file.size, air.File.systemCharset);
		stream.close();	

		return data;
	},
	
	/*******************************************
	 * protected methods
	 ***************************************/
	
	/**
	 * unbind a window event attached 
	 * @param {String} type		- the type of event to listen for
	 * @param {Function} event 	- the event registerd to liten for the given type
	 */
	_unbindAirWindowEvent: function (type, listener)
	{
		
		window.htmlControl.removeEventListener(type, listener);
		
		if( window.htmlControl.hasEventListener(type) && typeof listener == 'Function'	)
		{
			window.htmlControl.removeEventListener(type, listener);
		}	
		
	},
		
	/**
	 * renders an ul/li list based on a data input of an xml file
	 * in this case the main menu is rendered.. dom traversal throught the xml
	 * 
	 * @param {Object} data			- xml string containing the menupoints- name and links
	 * @param {Object} activeMenu	- the current active menu point gets a superspecial css class .. juhu
	 */
	_createMenuFromXML: function (data, activeMenu) {
		jamal.log("Start appController createMenuFromXML");
		
		var navi = '<ul class="tabs-nav">';		
		var name = '';
		var link = '';

		//This function will loop for each match on menu/item
		$("menu item", data).each(function () {
						
			name = $("name", this).text();
			link = $("link", this).text();
			( activeMenu == name) ? active = 'class="tabs-selected"' : active = "";
			
			navi += '<li ' + active + ' ><a href="' + link + '"><span>' + name + '</span></a></li>';
			//jamal.log( $("name", this).text());
					
		});
		
		navi +='</ul>';
		//append to navi div container
		$('#navi').append(navi);
		//append garbage collector onto navi
		$j.current.beforeWindowChange();
		
	}

});
